﻿'use strict';

/* Controllers */

app.controllersApp = angular.module('ishaCrmApp.controllers', ['ngCookies'])

app.controllersApp.controller('LoginController', ['$scope', '$rootScope', '$cookieStore', 'googleAuthService', function ($scope, $rootScope, $cookieStore, googleAuthService) {

    $scope.full_name = function () {
        return $.trim(($rootScope.profile && $rootScope.profile.given_name ? $rootScope.profile.given_name : '') + ' ' + ($rootScope.profile && $rootScope.profile.family_name ? $rootScope.profile.family_name : ''));
    };

    $scope.login = function () {
        googleAuthService.login().then(function (profileData) {
            if (profileData && profileData.email) {
                $rootScope.signIn(profileData);
            } else {
                $rootScope.loginDenied('ERROR-FETCHING-USER-PROFILE-DATA');
            }
        }, function (err) {
            $rootScope.loginDenied(err);
        });
    };

    $scope.logout = function() {
        $rootScope.signOut();
    }
}]);

app.controllersApp.run(['$rootScope', '$cookieStore', 'googleAuthService', function ($rootScope, $cookieStore, googleAuthService) {

    // Global Variables
    $rootScope.signin = false;
    $rootScope.profile = {};

    // Global events
    $rootScope.fireLoginEvent = function () { $rootScope.$emit('USER-LOGGED-IN-EVENT'); }
    $rootScope.fireDeniedEvent = function () { $rootScope.$emit('USER-LOGIN-DENIED'); }
    $rootScope.fireLogoutEvent = function () { $rootScope.$emit('USER-LOGGED-OUT-EVENT'); }

    // Global Function
    $rootScope.signIn = function (profileData) {
        $rootScope.signin = true;
        $cookieStore.put(app.CLIENT_ID, app.CookieValue);
        angular.extend($rootScope.profile, profileData);
        $rootScope.fireLoginEvent();
        //console.log(profileData);
    }

    $rootScope.signOut = function () {
        $cookieStore.remove(app.CLIENT_ID);
        gapi.auth.signOut();
        gapi.auth.setToken(null);
        $rootScope.signin = false;
        $rootScope.profile = {};
        $rootScope.fireLogoutEvent();
    }

    $rootScope.loginDenied = function (err) {
        $cookieStore.remove(app.CLIENT_ID);
        $rootScope.signin = false;
        $rootScope.profile = {};
        $rootScope.fireDeniedEvent();
        //console.log(err);
    }

    googleAuthService.checkLogin().then(function (profileData) {
        if (profileData && profileData.email) {
            $rootScope.signIn(profileData)
        }
    },
    function (err) {
        $rootScope.loginDenied(err);
    });

}]);

app.controllersApp.controller('ClientsController', ['$scope', '$rootScope', function ($scope, $rootScope) {

    $scope.clients = [];
    $scope.visible = false;
    $scope.errorMsg = '';

    // Listen to USER-LOGGED-IN-EVENT
    var userLoggedInEvent = $rootScope.$on('USER-LOGGED-IN-EVENT', function (event) {
        //console.log('Event fired - "USER-LOGGED-IN-EVENT"');
        gapi.client.crmdna.clientApi.getAll().execute(function (resp) {
            if (resp.statusCode == "SUCCESS") {
                $scope.$apply(function () {
                    $scope.clients = resp.object;
                    $scope.errorMsg = '';
                });
            } else {
                $scope.$apply(function () {
                    $scope.errorMsg = resp.statusCode;
                });
            }
        });
    });

    var userLoggedOutEvent = $rootScope.$on('USER-LOGGED-OUT-EVENT', function (event) {
        //console.log('Event fired - "USER-LOGGED-OUT-EVENT"');
        $scope.clients = [];
        $scope.visible = false;
    });

    // Unbind the event when the scope of this controller is destroyed
    $scope.$on('$destroy', userLoggedInEvent);
    $scope.$on('$destroy', userLoggedOutEvent);

}]);